import sys
import socket
from common import utils
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *

from ui.Ui_my_main_window import Ui_MainWindow#导入Ui文件
class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.ui = Ui_MainWindow()
        #加载Ui内容
        self.ui.setupUi(self)
        #初始化UI
        self.init_ui()
        
    @pyqtSlot()#防止多次连接按钮多次触发
    def on_btn_connect_clicked(self):#连接
        #获取用户输入的ip和端口
        mode = self.ui.cb_mode.currentText()
        target_ip = self.ui.edit_target_ip.text()
        target_port = self.ui.edit_target_port.text()
        print(f"连接{mode} {target_ip}:{target_port}")
        #创建socket对象
        tcp_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        #连接服务器
        tcp_client.connect((target_ip, int(target_port)))
        
        print("服务器连接成功")
        
        tcp_client.send("你好".encode())
        
        #阻塞接收信息，卡死在这里所以要用到子线程接收
        bytes_data = tcp_client.recv(1024)
        print(bytes_data)
        
        print("收到数据：",utils.decode_data)
        
        tcp_client.close()
    @pyqtSlot()   
    def on_btn_send_clicked(self):#发送
        print("发送")
        
    def init_ui(self):
        #初始化target_ip和target_port
        self.ui.edit_target_ip.setText("127.0.0.1")
        self.ui.edit_target_port.setText("8080")
        
        # self.ui.btn_connect.clicked.connect(self.on_btn_connect_clicked)
        
if __name__ == '__main__':
    app = QApplication(sys.argv)
    mywindow = MainWindow()
    mywindow.show()
    sys.exit(app.exec_())